//
//  JWKNetworkTools.swift
//  01-Swift封装网络请求
//
//  Created by 姜维克 on 16/5/22.
//  Copyright © 2016年 姜维克. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class JWKNetworkTools: AFHTTPSessionManager {

    static let sharedTools : JWKNetworkTools = {() -> (JWKNetworkTools) in
        
        let base = NSURL(string: API.hostName)
        let tools = JWKNetworkTools(baseURL: base)
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")

        return tools
    }()
}

//API接口
struct API{
   static let hostName = "https://api.weibo.com/"
   static let getUserAccessToken = "oauth2/access_token"
   static let getUserAccountInfo = "2/users/show.json"
   static let loadHomeStatusesData = "2/statuses/home_timeline.json"
}

extension JWKNetworkTools{
    
    func request(method:String, urlString:String, parameters:AnyObject?, finished:(responseObject:AnyObject?,error:NSError?)->()){
        
        //成功的回调
        let success = {(dataTask:NSURLSessionDataTask, response:AnyObject?)->()in
            finished(responseObject: response, error: nil)
        }
        
        //失败的回调
        let failure = {(dataTask:NSURLSessionDataTask?, error:NSError)->()in
            print(error)
            finished(responseObject: nil,error: error)
        }

        //GET请求
        if method == "GET"{
            self.GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
            
        //POST请求
        }else if method == "POST"{
            self.POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }
    
}

//获取token令牌分类
extension JWKNetworkTools{
   func getUserAccessToken(code:String,complete:(responseObject:AnyObject?,error:NSError?)->()){
        
        let parameters = ["client_id":client_id, "client_secret":client_secret, "grant_type":"authorization_code", "code":code,"redirect_uri":redirect_uri]
        
        
        JWKNetworkTools.sharedTools.request("POST", urlString: API.getUserAccessToken, parameters: parameters, finished: complete)
        
        //把闭包参数从viewModel的函数中传到networktools的封装的post请求函数中
   
    }
    
    
    func getUserAccountInfo(responseDict:[String : AnyObject],complete:(responseObject:AnyObject?,error:NSError?)->()){
    //能够get用户信息前提是上面的token等信息都获取了,实体内容不是空
    
    let access_token = responseDict["access_token"]!
    let uid = responseDict["uid"]!
    
    let parameters = ["access_token":access_token, "uid":uid]
    
    
    JWKNetworkTools.sharedTools.request("GET", urlString: API.getUserAccountInfo, parameters: parameters, finished: complete)

    }
 
}

//加载首页的微博状态分类
extension JWKNetworkTools{
    func loadHomeStatusesData(max_id:Int64, since_id:Int64, finished:(responseObject: AnyObject?, error: NSError?) -> ()){
        
        
        
        //如果access_token没有值
        guard let access_token = JWKUserAccountViewModel.sharedUserAccountViewModel.userAccount?.access_token else{
            return
        }
        
        //不能向字典中添加nil
        var parameters = ["access_token":access_token]
        
        //since_id 默认是0
        //若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
        if since_id > 0{
            parameters["since_id"] = "\(since_id)"
        }
        
        //max_id 若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
        //防止重复需要max-1
        if max_id > 0{
            parameters["max_id"] = "\(max_id-1)"
        }
        
        JWKNetworkTools.sharedTools.request("GET", urlString: API.loadHomeStatusesData, parameters: parameters, finished: finished)
        
        
    }
}